<template>
  <div>
    <Upload
      ref="upload"
      multiple
      action="https://upload-z2.qiniup.com"
      type="drag"
      :format="[ 'jpg','jpeg','png' ]"
      :show-file-list="true"
      :show-upload-list="true"
      :data="qiniuData"
      :on-success="handleAvatarSuccess"
      :on-preview="preview"
      :on-remove="handleAvatarRemove"
      :default-file-list="defaultList"
      :before-upload="beforeAvatarUpload"
    >
      <div style="padding: 40px 0;">
        <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
        <p>点击或拖拽上传6</p>
      </div>
    </Upload>

    <Modal title="预览图片" v-model="modal">
      <img style="width:100%" :src="modalImg" />
      <div slot="footer"></div>
    </Modal>
  </div>
</template>

<script>
export default {
  data() {
    return {
      qiniuData: {
        token: "",
        key: ""
      },

      defaultList: [],

      modalImg: "",
      modal: false
    };
  },
  props: {
    imgUrl: Array,
    clear: Boolean
  },
  watch: {
    clear: function(data) {
      this.$refs.upload.clearFiles();
      this.defaultList = [];
    },
    imgUrl: function(data) {
      this.defaultList = data;
    }
  },
  mounted() {
    this.getFilePrefix();
    this.getAccessToken();
  },
  methods: {
    // 预览
    preview(file) {
      console.log(file);
      this.modal = true;
      this.modalImg = this.prefix + file.url;
    },
    // 获取上传文件的前缀
    getFilePrefix() {
      this.$http(
        "/stage/protocol/getFilePrefix",
        {
          museumId: this.$store.state.museumId
        },
        "get",
        res => {
          if (res.data.code == 200) {
            this.qiniuData.key = res.data.data;
          } else {
            this.$Message.error(res.data.msg);
          }
        }
      );
    },
    // 获取上传文件token
    getAccessToken() {
      this.$http("/stage/file/getAccessToken", {}, "get", res => {
        if (res.data.code == 200) {
          this.qiniuData.token = res.data.data;
        } else {
          this.$Message.error(res.data.msg);
        }
      });
    },
    // 上传验证
    beforeAvatarUpload(file) {
      this.getFilePrefix();
      this.getAccessToken();
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isLt2M) {
        this.$Message.error("上传图片大小不能超过 1MB!");
      }
      return isLt2M;
    },
    // 上传完毕
    handleAvatarSuccess(res, file) {
      this.defaultList.push({
        name: file.name,
        url: res.key
      });
      this.$emit("uploadImg", this.defaultList);
    },
    // 移除
    handleAvatarRemove(res, file) {
      this.$http(
        "/stage/file/deleteFile",
        {
          fileName: res.url
        },
        "get",
        res => {
          if (res.data.code == 200) {
          } else {
            this.$Message.error(res.data.msg);
          }
        }
      );
      this.defaultList = file;
      this.$emit("uploadImg", this.defaultList);
    }
  }
};
</script>

<style scoped>
</style>